﻿//        Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.

using System;
using System.Linq;
using System.ServiceModel;

using MissedMemo.MeatAndCheeseDisc.OrderMonitor.OrderProcessing;


namespace MissedMemo.MeatAndCheeseDisc.OrderMonitor
{
    //[CallbackBehavior(UseSynchronizationContext=false)] ( not needed IF ALL COMMUNICATION IS 'OneWay' )
    public class OrderMonitorServiceAbstraction : IKitchenOrderMonitorServiceCallback
    {

    #region NewPizzaEventArgs...

        public class NewPizzaEventArgs : EventArgs
        {
            public Pizza Pizza { get; private set; }

            public NewPizzaEventArgs( Pizza pizza )
            {
                Pizza = pizza;
            }
        }

    #endregion (NewPizzaEventArgs)


        private KitchenOrderMonitorServiceClient _proxy = null;

        public event EventHandler<NewPizzaEventArgs> NewPizza;


        public OrderMonitorServiceAbstraction()
        {
            _proxy = new KitchenOrderMonitorServiceClient( new InstanceContext( this ) );

            try
            {
                _proxy.SubscribeOrderMonitorNotifications();
            }
            catch( EndpointNotFoundException e )
            {
                string strMsg = string.Format( "Service host must be running before starting the client.", e );
                System.Windows.MessageBox.Show( strMsg, "Service not found" );

                App.Current.Shutdown();
            }
        }


        // Relay notification of new pizza order to CLIENT WINDOW, to update UI

        public void OnNewPizza( int nowServingNumber, Pizza pizza )
        {
            if( NewPizza != null )
            {
                pizza.NowServingNumber = nowServingNumber;
                NewPizza( this, new NewPizzaEventArgs( pizza ) );
            }
        }


        public void OnCancelOrder( int orderID )
        {
            App.PizzaOrders.Where( pizza => pizza.NowServingNumber == orderID )
               .ToList().ForEach( pizza => pizza.IsCancelled = true );
        }


        public void NotifyPizzaIsDone( Pizza pizza )
        {
            _proxy.NotifyPizzaIsDone( pizza.NowServingNumber, pizza );
        }


        public void Close()
        {
            if( _proxy.State != CommunicationState.Faulted )
            {
                _proxy.UnsubscribeOrderMonitorNotifications();

                _proxy.Close();
                _proxy = null;
            }
        }
    }
}
